package com.example.demo;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.nio.charset.Charset;

public class APIHttpClientImpl {

  // �ӿڵ�ַ
  private static String apiURL = "http://localhost:9001//testjson";
  private static String pattern = "yyyy-MM-dd HH:mm:ss:SSS";
  private static HttpClient httpClient = new DefaultHttpClient();

  public static String sendByJsonStr(String url, String jsonParam) {
    HttpPost method = null;
    if (url != null) {
      apiURL = url;
    }
    method = new HttpPost(apiURL);

    return post(method, jsonParam);
  }

  /**
   * ���� API
   *
   * @param parameters
   * @return
   */
  public static String post(HttpPost method, String parameters) {

    long startTime = 0L;
    long endTime = 0L;
    int status = 0;
    String body = null;
    //		logger.info("parameters:" + parameters);

    if (method != null & parameters != null && !"".equals(parameters.trim())) {
      try {

        // ����һ��NameValuePair���飬���ڴ洢�����͵Ĳ���
        method.addHeader("Content-type", "application/json; charset=utf-8");
        method.setHeader("Accept", "application/json");

        StringEntity strEntity = new StringEntity(parameters, Charset.forName("UTF-8").toString());
        method.setEntity(strEntity);
        startTime = System.currentTimeMillis();
        HttpResponse response = httpClient.execute(method);

        endTime = System.currentTimeMillis();
        int statusCode = response.getStatusLine().getStatusCode();

        //				logger.info("statusCode:" + statusCode);
        //				logger.info("����API ����ʱ��(��λ������)��" + (endTime - startTime));
        if (statusCode != HttpStatus.SC_OK) {
          //					logger.error("Method failed:" + response.getStatusLine());
          status = 1;
        }

        // Read the response body
        body = EntityUtils.toString(response.getEntity());

      } catch (IOException e) {
        // �������
        status = 3;
      } finally {

        // д����־
        //		        LogOutputFile.loger(cType, message, result, data, AntConstant.LOGCODE);
        //		        LogVO logVO = LogOutputFile.assemableLogVO(cType, AntConstant.LOGCODE,
        // code,null,result,
        // map.get("inJson").toString(),message,InvocationInfoProxy.getInstance().getGroupId(),InvocationInfoProxy.getInstance().getGroupId());
        //		        CommonFetch fetch=new CommonFetch();
        //				fetch.getBasedao().insertVO(logVO);

      }
    }
    return body;
  }

  public static void main(String[] args) {
    APIHttpClientImpl.sendByJsonStr(null, "{\"id\":\"123\",\"name\":\"111\"}");
  }
}
